from flask import Flask
from flask import render_template
from flask import request
from datetime import timedelta
from flask import json
from flask import jsonify
import time
import httplib
import urllib
import MySQLdb
import os.path
import configparser
import logging


from DBUtils.PooledDB import PooledDB

config = configparser.ConfigParser()
config.read('./Conf/config.ini')
	
pool = PooledDB(MySQLdb,5,host=config['db']['db_host'],user=config['db']['db_user'],passwd=config['db']['db_password'],db=config['db']['db_name'],port=int(config['db']['db_port']))

#add logging config
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')

app = Flask(__name__)

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
#@app.route('/')
#def index():
#    return render_template('index.html',nav=1)

@app.route('/')
def newindex():
    return render_template('index_1.html',nav=1)

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'GET':
    	if 1 == 2:
        #if valid_login(request.form['username'],
         #              request.form['password']):
            # return log_the_user_in(request.form['username'])
		#else:
			error = 'Invalid username/password'
        else:
			error = '>>>>>>'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    # error = 'Invalid username/password'
    return render_template('login.html', error=error,method=request.method)

#@app.route('/save', methods=['GET','POST'])
def save():
	if request.method == 'GET':
		conn = pool.connection()
		# conn = MySQLdb.connect('localhost','root','xssd','xssd',charset='utf8')
		cursor = conn.cursor()
		cursor.execute('SELECT adm_name from xssd_admin where id = 2')
		data = cursor.fetchall()
		# return request # jsonify(request)

		cursor.close()
		conn.close()

	else:
		#result = request.form.keys
		print('>>>>>>>>>>>>>>>>>>')
		first_name = request.form.get('first_name', default='null')
		last_name = request.form.get('last_name', default='null')
		phone_number = request.form.get('phone_number', default='null')
		email_address = request.form.get('email_address', default='null')
		property_address = request.form.get('property_address', default='null')
		property_post_code = request.form.get('property_post_code', default='null')
		is_own_this_property = request.form.get('is_own_this_property', default='0')
		is_primary_residence = request.form.get('is_primary_residence', default='0')
		years_lived_here = request.form.get('years_lived_here', default=1)
		property_estimated_value = request.form.get('property_estimated_value', default='0')
		is_have_rental_component = request.form.get('is_have_rental_component', default='0')
		first_mortgage_balance = request.form.get('first_mortgage_balance', default='0')
		is_have_second_mortgage = request.form.get('is_have_second_mortgage', default='0')
		how_much_like_borrow = request.form.get('how_much_like_borrow', default='0')
		when_needed = request.form.get('when_needed', default='1900-01-01')
		your_birthdate = request.form.get('your_birthdate', default='1900-01-01')
		name_of_employer = request.form.get('name_of_employer', default='null')
		years_of_work = request.form.get('years_of_work', default='0')
		job_title = request.form.get('job_title', default='null')
		gross_annual_income = request.form.get('gross_annual_income', default='0')
		other_annual_income = request.form.get('other_annual_income', default='0')
		is_have_co_applicant = request.form.get('is_have_co_applicant', default='0')
		co_application_birthdate = request.form.get('co_application_birthdate', default='1900-01-01')
		first_name_c = request.form.get('first_name_c', default='null')
		last_name_c = request.form.get('last_name_c', default='null')
		name_of_employer_c = request.form.get('name_of_employer_c', default='null')
		years_of_work_c = request.form.get('years_of_work_c', default='0')
		job_title_c = request.form.get('job_title_c', default='null')
		gross_annual_income_c = request.form.get('gross_annual_income_c', default='0')
		other_annual_income_c = request.form.get('other_annual_income_c', default='0')
		how_payback_principal = request.form.get('how_payback_principal', default='null')
		how_pay_interest = request.form.get('how_pay_interest', default='null')
		apply_status = request.form.get('apply_status', default=0)
		apply_decline_info = request.form.get('apply_decline_info', default='')

		'''
		print first_name
		print last_name
		print phone_number
		print email_address
		print property_address
		print property_post_code
		print is_own_this_property
		print is_primary_residence
		print years_lived_here
		print property_estimated_value
		print is_have_rental_component
		print first_mortgage_balance
		print is_have_second_mortgage
		print how_much_like_borrow
		print when_needed
		print your_birthdate
		print name_of_employer
		print years_of_work
		print job_title
		print gross_annual_income
		print other_annual_income
		print is_have_co_applicant
		print co_application_birthdate
		print first_name_c
		print last_name_c
		print name_of_employer_c
		print years_of_work_c
		print job_title_c
		print gross_annual_income_c
		print other_annual_income_c
		print how_payback_principal
		print how_pay_interest
		print apply_status
		print apply_decline_info
		# prn_obj(request.form)
		'''
		try:
			conn = pool.connection()
			# conn = MySQLdb.connect('localhost','root','xssd','xssd',charset='utf8')
			cursor = conn.cursor()
			insert_sql = "INSERT INTO customers (first_name,last_name,phone_number,email_address,property_address,property_post_code,is_own_this_property,is_primary_residence,years_lived_here,property_estimated_value,is_have_rental_component,first_mortgage_balance,is_have_second_mortgage,how_much_like_borrow,when_needed,your_birthdate,name_of_employer,years_of_work,job_title,gross_annual_income,other_annual_income,is_have_co_applicant,co_application_birthdate,first_name_c,last_name_c,name_of_employer_c,years_of_work_c,job_title_c,gross_annual_income_c,other_annual_income_c,how_payback_principal,how_pay_interest,apply_status,apply_decline_info) VALUES (\
				'"+ MySQLdb.escape_string(first_name)+ "',\
				'"+ MySQLdb.escape_string(last_name) +"',\
				'"+ phone_number +"',\
				'"+ MySQLdb.escape_string(email_address) +"',\
				'"+ MySQLdb.escape_string(property_address) +"',\
				'"+ property_post_code+"',\
				'"+ is_own_this_property+"',\
				'"+ is_primary_residence +"',\
				'"+ years_lived_here +"',\
				'"+ property_estimated_value +"',\
				'"+ is_have_rental_component+"',\
				'"+ first_mortgage_balance+"',\
				'"+ is_have_second_mortgage+"',\
				'"+ how_much_like_borrow +"',\
				'"+ when_needed +"',\
				'"+ your_birthdate +"',\
				'"+ MySQLdb.escape_string(name_of_employer)+"',\
				'"+ years_of_work+"',\
				'"+ MySQLdb.escape_string(job_title)+"',\
				'"+ gross_annual_income+"',\
				'"+ other_annual_income+"',\
				'"+ is_have_co_applicant+"',\
				'"+ co_application_birthdate+"',\
				'"+ MySQLdb.escape_string(first_name_c)+"',\
				'"+ MySQLdb.escape_string(last_name_c)+"',\
				'"+ MySQLdb.escape_string(name_of_employer_c)+"',\
				'"+ years_of_work_c+"',\
				'"+ MySQLdb.escape_string(job_title_c)+"',\
				'"+ gross_annual_income_c+"',\
				'"+ other_annual_income_c+"',\
				'"+ MySQLdb.escape_string(how_payback_principal)+"',\
				'"+ MySQLdb.escape_string(how_pay_interest)+"',\
				'"+ apply_status+"',\
				'"+ MySQLdb.escape_string(apply_decline_info) +"')"
			#log insert sql statement
			logging.info(insert_sql)
			cursor.execute(insert_sql)
			cursor.close()
			conn.close()
		except (IOError ,ZeroDivisionError),x:
			print x
			#log exception
			logging.exception(x)
			return jsonify({'status':0})
		else:
			return jsonify({'status':1})
		# data = cursor.fetchall()
		# return request # jsonify(request)
# add by Fish
@app.route('/newsave', methods=['GET','POST'])
def newsave():
	if request.method == 'GET':
		conn = pool.connection()
		# conn = MySQLdb.connect('localhost','root','xssd','xssd',charset='utf8')
		cursor = conn.cursor()
		cursor.execute('SELECT adm_name from xssd_admin where id = 2')
		data = cursor.fetchall()
		# return request # jsonify(request)

		cursor.close()
		conn.close()

	else:
		#result = request.form.keys
		print('>>>>>>>>>>>>>>>>>>')
		first_name = request.form.get('first_name', default='null')
		last_name = request.form.get('last_name', default='null')
		phone_number = request.form.get('phone_number', default='null')
		email_address = request.form.get('email_address', default='null')
		
		property_estimated_value = request.form.get('property_estimated_value', default='0')
		first_mortgage_balance = request.form.get('first_mortgage_balance', default='0')
		how_much_like_borrow = request.form.get('how_much_like_borrow', default='0')
		when_needed = request.form.get('when_needed', default='1900-01-01')
		
		apply_status = request.form.get('apply_status', default=0)
		apply_decline_info = request.form.get('apply_decline_info', default='')

		try:
			conn = pool.connection()
			# conn = MySQLdb.connect('localhost','root','xssd','xssd',charset='utf8')
			cursor = conn.cursor()
			insert_sql = "INSERT INTO new_customers (first_name,last_name,phone_number,email_address,property_estimated_value,first_mortgage_balance,how_much_like_borrow,when_needed,apply_status,apply_decline_info) VALUES (\
				'"+ MySQLdb.escape_string(first_name)+ "',\
				'"+ MySQLdb.escape_string(last_name) +"',\
				'"+ phone_number +"',\
				'"+ MySQLdb.escape_string(email_address) +"',\
				'"+ property_estimated_value +"',\
				'"+ first_mortgage_balance+"',\
				'"+ how_much_like_borrow +"',\
				'"+ when_needed +"',\
				'"+ apply_status+"',\
				'"+ MySQLdb.escape_string(apply_decline_info) +"')"
			#log insert sql statement
			logging.info(insert_sql)
			cursor.execute(insert_sql)
			cursor.close()
			conn.close()
		except (IOError ,ZeroDivisionError),x:
			print x
			#log exception
			logging.exception(x)
			return jsonify({'status':0})
		else:
			return jsonify({'status':1})
		# data = cursor.fetchall()
		# return request # jsonify(request)

#add by Fish End

@app.route('/captchaVerify', methods=['GET','POST'])
def captchaVerify():
	# return jsonify({'status': 1, 'msg': 'verify success!'})
	import requests

	code = request.form.get('code', default='')
	# print('>>>>>>>>>>>>>')
	# print(code)

	reqdata={'response':code,'secret':'6LdpensUAAAAAMyi4DpVdDFVofw20noMhj95kc5-'}

	r = requests.post("https://www.google.com/recaptcha/api/siteverify", data=reqdata)
	
	if(r.status_code == 200):
		return jsonify({'status': 1, 'msg': 'verify success!'})
	else:
		return jsonify({'status': 0, 'msg': 'verify failed!'})

	# return jsonify({'status':res.status, 'msg': res.msg})

def prn_obj(obj):
	print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])

@app.route('/test', methods=['GET','POST'])
def test():
	code = request.form.get('code', default='')
	print('from test >>>>>>>>>>')
	print(code)
	return jsonify({'status':1, 'msg': 'hello'})

#@app.route('/success')		
def saveResultSuccess():
	return render_template('result_success.html')

#@app.route('/fail')	
def saveResultFail():
	return render_template('result_fail.html')
#add by Fish
@app.route('/newsuccess')		
def saveResultNewSuccess():
	return render_template('result_success_1.html')

@app.route('/newfail')	
def saveResultNewFail():
	return render_template('result_fail_1.html')
# add by Fish end

@app.route('/edit')
def edit():
	return render_template('edit.html')

def prn_obj(obj):
    print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])


@app.route('/about_us')
def aboutUs():
	return render_template('about_us.html',nav=2)

@app.route('/contact_us')
def contactUs():
	return render_template('contact_us.html',nav=4)

@app.route('/PurchasingYourHome')
def PurchasingYourHome():
	return render_template('services/service_01.html',nav=3, index =1)
@app.route('/PurchasingInvestment')
def PurchasingInvestment():
	return render_template('services/service_02.html',nav=3, index =2)
@app.route('/InvestmentRenovation')
def InvestmentRenovation():
	return render_template('services/service_03.html',nav=3, index =3)
@app.route('/LoanForBus')
def LoanForBus():
	return render_template('services/service_04.html',nav=3, index =4)
@app.route('/LoanForSelf')
def LoanForSelf():
	return render_template('services/service_05.html',nav=3, index =5)
@app.route('/LoanTemp')
def LoanTemp():
	return render_template('services/service_06.html',nav=3,index =6)
@app.route('/DebtConsolid')
def DebtConsolid():
	return render_template('services/service_07.html',nav=3,index =7)
@app.route('/Summary')
def Summary():
	print(time.time())
	return render_template('summary.html');

isDebug = False
if(config['server']['debug'] == 'True'):
	isDebug = True
	
app.run(debug=isDebug,host='0.0.0.0',port=int(config['server']['port']))
